package com.wlyuan.open.scanner.application.task.consignee;

import com.wlyuan.open.scanner.application.async.AsyncThreadUtils;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.dao.mapper.EndUserMapper;
import com.wlyuan.open.scanner.repository.ConsigneeRepository;
import com.wlyuan.open.scanner.repository.impl.BaseOrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.concurrent.CountDownLatch;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ConsigneeTaskHandler {
    private final EndUserMapper endUserMapper;
    private final ConsigneeRepository consigneeRepository;
    private final BaseOrderRepository baseOrderRepository;


    public void handler(Long tenantId) {
        StopWatch watch = new StopWatch();
        watch.start();
        var count = tenantId == null ? endUserMapper.count() : endUserMapper.countByTenantId(tenantId);
        logger.info("{}收货方老数据数据量，size：{}", tenantId == null ? "全量" : tenantId, count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        logger.info("{}收货方开始迁移，数据量：{},页数：{}", tenantId == null ? "全量" : tenantId, count, pages);
        CountDownLatch countDownLatch = new CountDownLatch(pages);
        for (int i = 1; i <= pages; i++) {
            ConsigneeTask task = new ConsigneeTask();
            task.setPageNum(i);
            task.setPageSize(Constants.PAGE_SIZE);
            task.setCountDownLatch(countDownLatch);
            task.setTenantId(tenantId);
            task.setEndUserMapper(endUserMapper);
            task.setConsigneeRepository(consigneeRepository);
            task.setBaseOrderRepository(baseOrderRepository);
            AsyncThreadUtils.getInstance().excute(task);
        }
        //等待所有线程完毕
        try {
            countDownLatch.await();
            watch.stop();
            logger.info("{}收货方任务迁移完成，数据量:{}, 页数:{}，耗时：{}秒", tenantId == null ? "全量" : tenantId, count, pages, watch.getTotalTimeSeconds());
        } catch (InterruptedException e) {
            logger.error("{}收货方数据迁移任务异常,{}", tenantId == null ? "全量" : tenantId, e);
            e.printStackTrace();
        }
    }
}
